using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using Subsync.Core.Subversion;
using org.tmatesoft.svn.core;
using org.tmatesoft.svn.core.wc;

namespace Subsync.Core.Subversion
{
	/// <summary>
	/// Author: Juin Min
	/// </summary>
	public class SVNPropGet : CommandBase
	{
		private SVNRevision peg_revision = SVNRevision.UNDEFINED;
		private SVNRevision revision = SVNRevision.WORKING;
		private string prop_name;
		private java.io.File localpath;
		private SVNURL repospath;
		private bool WConly;
        private string prop_value;

        public string value
        {
            get { return prop_value; }
        }

        public SVNPropGet(string working_path, string prop_name, string peg_rev, string target_rev)
		{
			Debug.WriteLine ("SVN propget std constructor");
			WConly = this.checkPath (working_path);
			if (WConly)
            {
				localpath = new java.io.File (working_path);
				repospath = null;
			}
            else
            {
				localpath = null;
				repospath = SVNURL.parseURIEncoded (working_path);
			}
			
			this.prop_name = prop_name;
			this.peg_revision = SVNRevision.parse(peg_rev);
			this.revision = SVNRevision.parse(target_rev);
		}

		public override void Execute ()
		{
            Debug.WriteLine ("SVN PropGet Execution");
						
			// Setup library
			Tools.SetupLibrary ();
			
			// Setup clients
			SVNClientManager cm = SVNClientManager.newInstance ();
			SVNWCClient wcclient = cm.getWCClient ();
			
			try {
                SVNPropertyData res;
				if (WConly)
                {
					// input path leads to sth in WC
					res = wcclient.doGetProperty (localpath, prop_name, peg_revision, revision);
				}
                else
                {
					// input path leads to sth in repos
					res = wcclient.doGetProperty (repospath, prop_name, peg_revision, revision);
				}

                if (res != null)
                    this.prop_value = res.getValue().toString();
                else
                    this.prop_value = "";
				
			} catch (SVNException exptn) {
				throw new SVNExecuteException (exptn.getMessage ());
			}
			
		}

		public bool checkPath (string inputPath)
		{
			// Checks if path is for repos access or WC access
			// Returns true for WC access (used for bool member WCOnly)
			Debug.WriteLine ("SVN propget method to check if input path is repos access");
			List<string> repos_access = new List<string> ();
			// List of Repos access URLs
			repos_access.Add ("file:///");
			// Local repos
			repos_access.Add ("http://");
			repos_access.Add ("https://");
			repos_access.Add ("svn://");
			repos_access.Add ("svn+ssh://");
			
			foreach (string accessprefix in repos_access) {
				if (inputPath.StartsWith (accessprefix))
					return false;
			}
			
			return true;
		}
	}
}
